package controllers.user;

import javax.persistence.PersistenceException;

import models.Role;
import models.User;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import controllers.routes;
import controllers.advertisement.AdvertisementController;
import controllers.buy.Cart;
import controllers.order.OrderController;

/**
 * @class UserController
 * @author andris
 * 
 */
public class UserController extends Controller {

	static Form<User> userForm = form(User.class);

	/**
	 * Users
	 * 
	 * @return ok(views.html.users.render(User.all(), userForm));
	 */
	public static Result users() {
		if (getCurrentUser().getPriv("admin")) {
			return ok(views.html.user.users.render(User.all(), userForm));
		} else {
			return redirect(controllers.user.routes.UserController.logIn());
		}
	}

	public static Result newUser() {
		Form<User> filledForm = userForm.bindFromRequest();
		if (filledForm.hasErrors()) {
			return badRequest(views.html.user.signUp.render(filledForm, ""));
		} else {
			User u = filledForm.get();
			// u.setRole(Ebean.find(Role.class, 3));
			u.setRole(Role.find.where().like("name", "user").findUnique());
			try {
				User.create(u);

			} catch (PersistenceException e) {
				return ok((views.html.user.signUp.render(userForm,
						"*account name already used")));
			}
			final User umail = u;
			Thread sendMailThread = new Thread(new Runnable() {
				@Override
				public void run() {
					EmailSender.sendMail(umail);
				}
			});
			sendMailThread.run();
			return ok(views.html.user.logIn.render(userForm,
					"Registry Success!"));
		}
	}

	public static Result redirectToList() {
		return redirect(controllers.user.routes.UserController.users());
	}

	public static Result deleteUser(Long id) {
		User.delete(id);
		return redirectToList();
	}

	public static Result logIn() {

		if (null != session("currentUserEmail")) {
			return redirect(routes.Application.index());
		}
		User loginUser = userForm.bindFromRequest().get();
		User registeredUser = User.find.where()
				.like("email", loginUser.getEmail())
				.like("password", loginUser.getPassword()).findUnique();

		if (null == registeredUser) {
			return ok(views.html.user.logIn.render(userForm, null));
		} else {
			session("currentUserEmail", registeredUser.getEmail());
			return redirect(routes.Application.index());
		}
	}

	public static Result signUp() {
		return ok(views.html.user.signUp.render(userForm, null));
	}

	public static Result chgPsw() {
		if (null == session("currentUserEmail")) {
			return redirect(routes.Application.index());
		}
		Form<User> filledForm = userForm.bindFromRequest();
		filledForm.data().put("email", session("currentUserEmail"));
		User u = new User();
		u.equals(UserController.getCurrentUser());
		try {
			if (filledForm.get().getPassword()
					.equals(UserController.getCurrentUser().getPassword())) {
				// if(filledForm.get().getNewpassword().equals(filledForm.get().getRepassword())){
				if (filledForm.get().checkPsw()) {
					u.setPassword(filledForm.get().getNewpassword());
					u.update(UserController.getCurrentUser().getId());

					// flash("success",
					// UserController.getCurrentUser().getEmail() +
					// " password has been changed!");
					return redirect(routes.Application.index());
				}
				return ok(views.html.user.chgPsw
						.render(filledForm,
								"New password and Re-password are not match, or these fields are empty!"));
			} else {
				return ok(views.html.user.chgPsw.render(filledForm,
						"Old password is incorrect!"));
			}

		} catch (NullPointerException e) {
			filledForm.get().setNewpassword(null);
			filledForm.get().setRepassword(null);
		}
		return ok(views.html.user.chgPsw.render(filledForm, null));
	}

	public static Result myOrders() {
		String user = session("currentUserEmail");
		if (user != null) {
			return OrderController.orders(getCurrentUser());
		}
		return redirect(controllers.user.routes.UserController.logIn());
	}

	public static Result myAds() {
		String user = session("currentUserEmail");
		if (user != null) {
			return AdvertisementController.ads(getCurrentUser());
		}
		return redirect(controllers.user.routes.UserController.logIn());
	}

	public static User getCurrentUser() {
		String email = session("currentUserEmail");
		if (null == email) {
			return null;
		}
		return User.find.where().like("email", email).findUnique();
	}

	public static Result logOut() {
		Cart usercart = Cart.getUserCart(session("currentUserEmail"));
		if (null != usercart) {
			usercart.clear(); // TODO nem feltetlen muszaj uriteni
		}
		session().remove("currentUserEmail");
		return redirect(routes.Application.index());
	}
}